<template>
  <div class="recruiter-dashboard-container">
    <a-card title="招聘数据分析" :bordered="false">
      <!-- 面试次数和面试人数趋势 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="面试趋势统计" :bordered="false">
            <div v-if="hasInterviewCountData" class="chart-container">
              <v-chart class="chart" :option="interviewTrendOption" autoresize />
            </div>
            <a-empty v-else description="暂无面试趋势数据" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 通过率趋势 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="面试通过率趋势" :bordered="false">
            <div v-if="hasPassRateData" class="chart-container">
              <v-chart class="chart" :option="passRateTrendOption" autoresize />
            </div>
            <a-empty v-else description="暂无通过率数据" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 面试邀约趋势 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="面试邀约趋势" :bordered="false">
            <div v-if="hasInviteCountData" class="chart-container">
              <v-chart class="chart" :option="inviteTrendOption" autoresize />
            </div>
            <a-empty v-else description="暂无面试邀约数据" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 职位通过率对比 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="职位通过率对比" :bordered="false">
            <div class="date-selector">
              <a-date-picker
                v-model:value="selectedPositionDate"
                :disabled-date="disabledDate"
                @change="handlePositionDateChange"
                placeholder="选择日期"
              />
              <span class="selected-date-text" v-if="formattedPositionDate">
                当前查询: {{ formattedPositionDate }}
              </span>
            </div>
            <div v-if="hasPositionPassRateData" class="chart-container">
              <v-chart class="chart" :option="positionPassRateOption" autoresize />
            </div>
            <a-empty v-else :description="`${formattedPositionDate || '选定日期'} 暂无职位通过率数据`" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 技术领域-职位面试次数分布 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="技术领域-职位面试分布" :bordered="false">
            <div class="date-selector">
              <a-date-picker
                v-model:value="selectedFieldPositionDate"
                :disabled-date="disabledDate"
                @change="handleFieldPositionDateChange"
                placeholder="选择日期"
              />
              <span class="selected-date-text" v-if="formattedFieldPositionDate">
                当前查询: {{ formattedFieldPositionDate }}
              </span>
            </div>
            <div v-if="hasFieldPositionData" class="field-chart-container">
              <v-chart class="field-chart" :option="fieldPositionOption" autoresize />
            </div>
            <a-empty v-else :description="`${formattedFieldPositionDate || '选定日期'} 暂无技术领域-职位分布数据`" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <!-- 高校分布 -->
      <a-row :gutter="[16, 16]">
        <a-col :span="24">
          <a-card title="高校人才分布" :bordered="false">
            <div class="date-selector">
              <a-date-picker
                v-model:value="selectedUniversityDate"
                :disabled-date="disabledDate"
                @change="handleUniversityDateChange"
                placeholder="选择日期"
              />
              <span class="selected-date-text" v-if="formattedUniversityDate">
                当前查询: {{ formattedUniversityDate }}
              </span>
            </div>
            <div v-if="hasUniversityData" class="chart-container">
              <v-chart class="chart" :option="universityOption" autoresize />
            </div>
            <a-empty v-else :description="`${formattedUniversityDate || '选定日期'} 暂无高校分布数据`" />
          </a-card>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart, TreemapChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserstore'
import {
  getInterviewCountByCompanyUsingGet,
  getInterviewUserCountUsingGet,
  getOnlineInterviewInviteCountUsingGet,
  getPassRateByCompanyUsingGet,
  getPassRateByCompanyPositionUsingGet,
  getInterviewCountByCompanyFieldPositionUsingGet,
  getUniversityDistributionByCompanyUsingGet
} from '@/api/echartsController'

// 注册必要的组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  TreemapChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
])

// 获取用户信息和公司
const userStore = useLoginUserStore()
const company = userStore.loginUser.company

// 基本数据状态
const interviewCountData = ref<any[]>([])
const interviewUserCountData = ref<any[]>([])
const inviteCountData = ref<any[]>([])
const passRateData = ref<any[]>([])
const positionPassRateData = ref<any[]>([])
const fieldPositionData = ref<any[]>([])
const universityData = ref<any[]>([])

// 日期选择状态
const selectedPositionDate = ref<any>(dayjs().subtract(1, 'day'))
const formattedPositionDate = ref<string>('')
const selectedFieldPositionDate = ref<any>(dayjs().subtract(1, 'day'))
const formattedFieldPositionDate = ref<string>('')
const selectedUniversityDate = ref<any>(dayjs().subtract(1, 'day'))
const formattedUniversityDate = ref<string>('')

// 数据状态检查
const hasInterviewCountData = computed(() => {
  return interviewCountData.value && interviewCountData.value.length > 0
})

const hasPassRateData = computed(() => {
  return passRateData.value && passRateData.value.length > 0
})

const hasInviteCountData = computed(() => {
  return inviteCountData.value && inviteCountData.value.length > 0
})

const hasPositionPassRateData = computed(() => {
  return positionPassRateData.value && positionPassRateData.value.length > 0
})

const hasFieldPositionData = computed(() => {
  return fieldPositionData.value && fieldPositionData.value.length > 0
})

const hasUniversityData = computed(() => {
  return universityData.value && universityData.value.length > 0
})

// 禁用未来日期
const disabledDate = (current: any) => {
  return current && current > dayjs().endOf('day')
}

// 面试趋势图表配置
const interviewTrendOption = computed(() => {
  if (!hasInterviewCountData.value) return {}

  const dates = interviewCountData.value.map((item) => item.dt)
  const interviewCounts = interviewCountData.value.map((item) => item.interview_count)
  const userCounts = interviewUserCountData.value.map((item) => item.interview_user_count)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['面试次数', '面试人数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '面试次数',
        type: 'line',
        data: interviewCounts,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#1890ff'
        },
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '面试人数',
        type: 'line',
        data: userCounts,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#52c41a'
        },
        itemStyle: {
          color: '#52c41a'
        }
      }
    ]
  }
})

// 通过率趋势图表配置
const passRateTrendOption = computed(() => {
  if (!hasPassRateData.value) return {}

  const dates = passRateData.value.map((item) => item.dt)
  const passRates = passRateData.value.map((item) => (item.pass_rate * 100).toFixed(2))
  const interviewTotals = passRateData.value.map((item) => item.interview_total)
  const passTotals = passRateData.value.map((item) => item.pass_total)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        const date = params[0].axisValue
        const total = params[0].data
        const pass = params[1].data
        const rate = params[2].data
        return `日期: ${date}<br/>面试总数: ${total}<br/>通过数: ${pass}<br/>通过率: ${rate}%`
      }
    },
    legend: {
      data: ['面试总数', '通过数', '通过率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '通过率(%)',
        position: 'right',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '面试总数',
        type: 'bar',
        data: interviewTotals,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '通过数',
        type: 'bar',
        data: passTotals,
        itemStyle: {
          color: '#52c41a'
        }
      },
      {
        name: '通过率',
        type: 'line',
        yAxisIndex: 1,
        data: passRates,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#faad14'
        },
        itemStyle: {
          color: '#faad14'
        }
      }
    ]
  }
})

// 邀约趋势图表配置
const inviteTrendOption = computed(() => {
  if (!hasInviteCountData.value) return {}

  const dates = inviteCountData.value.map((item) => item.dt)
  const inviteCounts = inviteCountData.value.map((item) => item.invite_user_count)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '邀约人数'
    },
    series: [
      {
        name: '邀约人数',
        type: 'bar',
        data: inviteCounts,
        itemStyle: {
          color: function(params: any) {
            // 颜色渐变
            const colorList = ['#91d5ff', '#69c0ff', '#40a9ff', '#1890ff', '#096dd9', '#0050b3', '#003a8c']
            return colorList[params.dataIndex % colorList.length]
          }
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  }
})

// 职位通过率图表配置
const positionPassRateOption = computed(() => {
  if (!hasPositionPassRateData.value) return {}

  const positions = positionPassRateData.value.map((item) => item.position_name)
  const passRates = positionPassRateData.value.map((item) => (item.pass_rate * 100).toFixed(2))
  const candidateCounts = positionPassRateData.value.map((item) => item.candidate_count)

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        const position = params[0].axisValue
        const candidates = params[0].data
        const rate = params[1].data
        return `职位: ${position}<br/>候选人数: ${candidates}<br/>通过率: ${rate}%`
      }
    },
    legend: {
      data: ['候选人数', '通过率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: positions,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '候选人数',
        position: 'left'
      },
      {
        type: 'value',
        name: '通过率(%)',
        position: 'right',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '候选人数',
        type: 'bar',
        data: candidateCounts,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '通过率',
        type: 'line',
        yAxisIndex: 1,
        data: passRates,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#52c41a'
        },
        itemStyle: {
          color: '#52c41a'
        },
        label: {
          show: true,
          formatter: '{c}%'
        }
      }
    ]
  }
})

// 技术领域-职位面试次数分布图表配置
const fieldPositionOption = computed(() => {
  if (!hasFieldPositionData.value) return {}

  // 按技术领域分组数据
  const groupedData: { [key: string]: any[] } = {}
  fieldPositionData.value.forEach((item) => {
    if (!groupedData[item.tech_field]) {
      groupedData[item.tech_field] = []
    }
    groupedData[item.tech_field].push({
      name: item.position_name,
      value: item.interview_count
    })
  })

  // 构建树形图数据
  const treeData = []
  for (const field in groupedData) {
    treeData.push({
      name: field,
      children: groupedData[field]
    })
  }

  return {
    tooltip: {
      formatter: function (info: any) {
        const value = info.value
        const name = info.name
        const treePathInfo = info.treePathInfo

        if (treePathInfo.length > 1) {
          const techField = treePathInfo[0].name
          return `<div>${techField} - ${name}</div>` + `<div>面试次数: ${value}</div>`
        }

        return `<div>${name}</div>`
      }
    },
    series: [
      {
        name: '技术领域-职位分布',
        type: 'treemap',
        data: treeData,
        leafDepth: 1,
        levels: [
          {
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              gapWidth: 2
            }
          },
          {
            colorSaturation: [0.3, 0.6],
            itemStyle: {
              borderColorSaturation: 0.7,
              gapWidth: 2,
              borderWidth: 2
            }
          }
        ],
        breadcrumb: {
          show: false
        }
      }
    ]
  }
})

// 高校分布图表配置
const universityOption = computed(() => {
  if (!hasUniversityData.value) return {}

  const universities = universityData.value.map((item) => item.university_name)
  const userCounts = universityData.value.map((item) => item.user_count)

  // 为饼图准备数据
  const pieData = universityData.value.map((item) => ({
    name: item.university_name,
    value: item.user_count
  }))

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: universities
    },
    series: [
      {
        name: '高校分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: pieData
      }
    ]
  }
})

// 获取所有数据
const fetchAllData = async () => {
  try {
    // 获取面试次数数据
    const interviewCountResult = await getInterviewCountByCompanyUsingGet({ companyName:company as any })
    if (interviewCountResult.code === 0 && interviewCountResult.data) {
      interviewCountData.value = interviewCountResult.data as any
    }

    // 获取面试人数数据
    const interviewUserCountResult = await getInterviewUserCountUsingGet({ companyName:company as any })
    if (interviewUserCountResult.code === 0 && interviewUserCountResult.data) {
      interviewUserCountData.value = interviewUserCountResult.data as any
    }

    // 获取邀约数据
    const inviteCountResult = await getOnlineInterviewInviteCountUsingGet({ company:company as any })
    if (inviteCountResult.code === 0 && inviteCountResult.data) {
      inviteCountData.value = inviteCountResult.data as any
    }

    // 获取通过率数据
    const passRateResult = await getPassRateByCompanyUsingGet({ companyName:company as any })
    if (passRateResult.code === 0 && passRateResult.data) {
      passRateData.value = passRateResult.data as any
    }

    // 获取初始职位通过率数据
    const yesterdayDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    formattedPositionDate.value = yesterdayDate
    await fetchPositionPassRate(yesterdayDate)

    // 获取初始技术领域-职位分布数据
    formattedFieldPositionDate.value = yesterdayDate
    await fetchFieldPositionData(yesterdayDate)

    // 获取初始高校分布数据
    formattedUniversityDate.value = yesterdayDate
    await fetchUniversityData(yesterdayDate)
  } catch (error) {
    message.error('获取数据失败，请稍后重试')
    console.error('数据获取错误:', error)
  }
}

// 获取职位通过率数据
const fetchPositionPassRate = async (date: string) => {
  try {
    const result = await getPassRateByCompanyPositionUsingGet({
      companyName:company as any ,
      date
    })
    if (result.code === 0 && result.data) {
      positionPassRateData.value = result.data as any
    } else {
      positionPassRateData.value = []
      message.warning(`${date} 暂无职位通过率数据`)
    }
  } catch (error) {
    positionPassRateData.value = []
    message.error('获取职位通过率数据失败')
  }
}

// 获取技术领域-职位分布数据
const fetchFieldPositionData = async (date: string) => {
  try {
    const result = await getInterviewCountByCompanyFieldPositionUsingGet({
      companyName:company as any,
      date
    })
    if (result.code === 0 && result.data) {
      fieldPositionData.value = result.data as any
    } else {
      fieldPositionData.value = []
      message.warning(`${date} 暂无技术领域-职位分布数据`)
    }
  } catch (error) {
    fieldPositionData.value = []
    message.error('获取技术领域-职位分布数据失败')
  }
}

// 获取高校分布数据
const fetchUniversityData = async (date: string) => {
  try {
    const result = await getUniversityDistributionByCompanyUsingGet({
      companyName:company as any,
      date
    })
    if (result.code === 0 && result.data) {
      universityData.value = result.data as any
    } else {
      universityData.value = []
      message.warning(`${date} 暂无高校分布数据`)
    }
  } catch (error) {
    universityData.value = []
    message.error('获取高校分布数据失败')
  }
}

// 处理职位通过率日期变更
const handlePositionDateChange = async (date: any) => {
  if (!date) {
    positionPassRateData.value = []
    formattedPositionDate.value = ''
    return
  }

  formattedPositionDate.value = dayjs(date).format('YYYY-MM-DD')
  await fetchPositionPassRate(formattedPositionDate.value)
}

// 处理技术领域-职位分布日期变更
const handleFieldPositionDateChange = async (date: any) => {
  if (!date) {
    fieldPositionData.value = []
    formattedFieldPositionDate.value = ''
    return
  }

  formattedFieldPositionDate.value = dayjs(date).format('YYYY-MM-DD')
  await fetchFieldPositionData(formattedFieldPositionDate.value)
}

// 处理高校分布日期变更
const handleUniversityDateChange = async (date: any) => {
  if (!date) {
    universityData.value = []
    formattedUniversityDate.value = ''
    return
  }

  formattedUniversityDate.value = dayjs(date).format('YYYY-MM-DD')
  await fetchUniversityData(formattedUniversityDate.value)
}

onMounted(() => {
  // 获取基本数据
  fetchAllData()
})
</script>

<style scoped>
.recruiter-dashboard-container {
  padding: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.field-chart-container {
  height: 500px;
  width: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}

.field-chart {
  width: 100%;
  height: 100%;
}

.date-selector {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.selected-date-text {
  margin-left: 16px;
  color: #8c8c8c;
}

:deep(.ant-card-head-title) {
  font-weight: bold;
  color: #1890ff;
}
</style>
